/*
 * Copyright 2009 Jamie Gennis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.ggdi;

import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import java.lang.reflect.Method;

/**
 * A servlet that dispatches old-style GWT RPC calls (i.e. {@code
 * RemoteService} calls) to a Guice-injected instance of the remote service
 * interface.
 *
 * @author jgennis
 */
@Singleton
public class GgdiRemoteServiceServlet extends RemoteServiceServlet {

  @Inject
  Injector injector;

  @Override
  public String processCall(String payload) throws SerializationException {
    try {
      RPCRequest rpcRequest = RPC.decodeRequest(payload, null, this);
      Method rpcMethod = rpcRequest.getMethod();
      Class<?> rpcIntf = rpcMethod.getDeclaringClass();
      Object rpcImpl = injector.getInstance(rpcIntf);
      return RPC.invokeAndEncodeResponse(rpcImpl, rpcMethod, rpcRequest.getParameters(),
          rpcRequest.getSerializationPolicy(), rpcRequest.getFlags());
    } catch (IncompatibleRemoteServiceException ex) {
      log("An IncompatibleRemoteServiceException was thrown while processing this call.", ex);
      return RPC.encodeResponseForFailure(null, ex);
    }
  }
}
